// 页面操作记录
import { ref, computed, watch } from 'vue'
import { createSharedComposable, useRefHistory } from '@vueuse/core'
import { useEditStore } from '@/store'
import { deepClone } from '@/libs/tools'

const usePageHistoryFun = () => {
    const editStore = useEditStore()

    // 当前控件列表
    const widgetList = computed({
        get: () => editStore.widgetList,
        set: val => editStore.setWidgetList(val)
    })
    // 当前选中的控件ID
    const selectWidgetIds = computed({
        get: () => editStore.selectWidgetIds,
        set: val => editStore.selectWidgetIds = val
    })

    // 初始值
    const targetData = ref({
        widgetList: widgetList.value,
        selectWidgetIds: selectWidgetIds.value
    })
    // 历史记录
    const refHistory = useRefHistory(targetData, {
        dump: deepClone
    })

    // 是否可以回退当前操作记录
    const isBackPageHistory = computed(() => refHistory.canUndo.value)
    // 是否可以前进当前操作记录
    const isForwardPageHistory = computed(() => refHistory.canRedo.value)

    // 当前页面id
    const pageId = computed(() => editStore.pageId)

    watch(pageId, (newValue, oldValue) => {
        resetPageHistory()
    })

    // 重置历史记录
    const resetPageHistory = () => {
        onAddPageHistory()
        refHistory.clear()
    }

    // 添加页面操作记录
    const onAddPageHistory = () => {
        targetData.value = {
            widgetList: widgetList.value,
            selectWidgetIds: selectWidgetIds.value
        }
        refHistory.commit()
        console.log('添加页面操作记录')
    }

    // 恢复当前页面指定的操作记录
    const onRecoveryPageHistory = status => {
        if (status) {
            refHistory.redo()
        } else {
            refHistory.undo()
        }
        widgetList.value = deepClone(targetData.value.widgetList)
        selectWidgetIds.value = deepClone(targetData.value.selectWidgetIds)
    }

    // 回退当前页面指定的操作记录
    const onBackPageHistory = () => {
        onRecoveryPageHistory(false)
    }

    // 前进当前页面指定的操作记录
    const onForwardPageHistory = () => {
        onRecoveryPageHistory(true)
    }

    return {
        isBackPageHistory,
        isForwardPageHistory,
        onAddPageHistory,
        onRecoveryPageHistory,
        onBackPageHistory,
        onForwardPageHistory
    }
}

// createSharedComposable 使一个可组合的函数可用于多个 Vue 实例（将重用以前的状态，并且不会注册新的事件侦听器）
const usePageHistory = createSharedComposable(usePageHistoryFun)

export default usePageHistory